const express = require('express');
const multer = require('multer');
const path = require('path');
const router = express.Router();
const db = require('../db/index');
const verifyToken = require("../utils/verifyToken"); // 假设这是数据库连接模块

// 设置存储路径
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'public/img/userAvatar/');
    },
    filename: (req, file, cb) => {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        cb(null, uniqueSuffix + path.extname(file.originalname));
    }
});
const upload = multer({ storage: storage });

// 头像上传接口
router.post('/upload/modifyAvatar', verifyToken, upload.single('avatar'), async (req, res) => {
    try {
        const userType = req.user.role;
        const userId = req.user.id;

        const filePath = `${req.file.filename}`; // 文件相对路径
        console.log(userType, userId);
        // 更新数据库中的 avatar_url 字段
        const tableName = userType === 'student' ? 'student' : 'admin';
        const userIdField = userType === 'student' ? 'id' : 'adminId';

        const sql = `UPDATE ${tableName} SET avatar_url = ? WHERE ${userIdField} = ?`;
        await db.query(sql, [filePath, userId]);

        res.json({ success: true, message: '头像上传成功', filePath });
    } catch (error) {
        console.error('上传头像失败', error);
        res.status(500).json({ success: false, message: '上传头像失败' });
    }
});

module.exports = router;
